package admin_service

import (
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/genutil"
	"shop/utils/result"
)

func GetSysUserList() *result.Result {
	list := make([]*entity.SysUser, 0, 0)
	// TODO 使用join查询
	dao.GetDB().Table(entity.TableNameSysUser).Find(&list)
	for _, user := range list {
		user.RoleIdList = make([]int, 0, 0)
		convertutil.ParseJson(user.RoleIdListStr, &user.RoleIdList)
		for _, roleId := range user.RoleIdList {
			roleName := ""
			dao.GetDB().Table(entity.TableNameSysRole).Select("name").Where("id", roleId).Take(&roleName)
			if len(user.RoleNames) > 0 {
				user.RoleNames += ","
			}
			user.RoleNames += roleName
		}

	}
	return result.Ok(list)
}

func AddSysUser(sysUser *entity.SysUser) *result.Result {
	sysUser.Status = constant.UserStatusNormal
	sysUser.Salt = genutil.RandStr(20)
	password := genutil.RandStr(6)
	sysUser.Password = genutil.Md5HexWithSalt(password, sysUser.Salt)
	dao.GetTx().Model(sysUser).Create(sysUser).Commit()
	return result.Ok(password)
}

func UpdateSysUser(userId int64, sysUser *entity.SysUser) *result.Result {
	if sysUser.RoleIdList != nil && len(sysUser.RoleIdList) > 0 {
		sysUser.RoleIdListStr = convertutil.ToJsonString(sysUser.RoleIdList)
	}
	rows := dao.GetTx().Model(sysUser).Where("id", userId).Updates(sysUser).Commit().RowsAffected
	return result.Ok(rows)
}

func DeleteSysUser(id int) *result.Result {
	rows := dao.GetTx().Table(entity.TableNameSysUser).Where("id", id).Delete(nil).Commit().RowsAffected
	return result.Ok(rows)
}
